package com.comment.interceptor;

import com.comment.annotation.AccessLimit;
import com.comment.common.ResultCode;
import com.comment.common.exception.CustomException;
import com.comment.config.model.Audience;
import com.comment.util.JwtTokenUtil;
import com.comment.util.RedisUtils;
import com.comment.util.SpringUtil;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioInputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author vedeng
 * @className FangshuaInterceptor
 * @description:
 * @date 2021/12/21 14:45
 */
public class FangshuaInterceptor extends HandlerInterceptorAdapter {

   /* @Autowired
    private RedisUtils redisUtils;*/
   private final RedisUtils redisUtils = SpringUtil.getBean(RedisUtils.class);

    @Autowired
    private Audience audience;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        //判断请求是否属于方法的请求
        /*if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            //获取方法中的注解,看是否有该注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if(accessLimit == null){
                return true;
            }

            if (audience == null){
                BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
                audience = (Audience)factory.getBean("audience");
            }

            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            boolean login = accessLimit.needLogin();
            String key = request.getRequestURI();
            String authHeader = request.getHeader(JwtTokenUtil.AUTH_HEADER_KEY);
            String token = authHeader.substring(7);
            String userId = JwtTokenUtil.getUserId(token, audience.getBase64Secret());
            //如果需要登录
            if(login){
                key+="" + userId;
            }

            //从redis中获取用户访问的次数(redis中保存的key保存3(seconds)秒，redisUtils使用的单位是秒，意思是3秒内重复请求接口限制次数)
            Integer count = redisUtils.get(key,Integer.class,seconds);
            if(count == null){
                //第一次访问
                redisUtils.set(key,1,3);
            }else if(count < maxCount){
                //加1
                redisUtils.incr(key, 1);
            }else{
                //超出访问次数
                throw new CustomException(ResultCode.COUNT_TIME_ERROR);
            }
        }*/
        return true;
    }

}